package jee.boot.module.oauth2.auth;

import jee.boot.entity.auth.Account;
import jee.boot.common.utils.HttpServletHolder;
import jee.boot.common.utils.SpringContextHolder;
import jee.boot.common.utils.StringUtils;
import jee.boot.module.oauth2.config.UserDetailHandler;
import jee.boot.module.oauth2.service.AccountService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.servlet.http.HttpServletRequest;

import jee.boot.entity.auth.AuthConstant;

/**
 * 登录授权查询用户信息
 */
public class CustomUserDetailHandler implements UserDetailHandler {
    private RedisTemplate<String, Object> redisTemplate;

    public CustomUserDetailHandler() {
    }

    public CustomUserDetailHandler(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 按登录名称查询用户
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AccountService accountService = SpringContextHolder.getApplicationContext().getBean(AccountService.class);
        Account query = new Account();
        query.setUsername(username);
        Account login = accountService.findListForLogin(query);//find user by username/email/phone
        HttpServletRequest request = HttpServletHolder.getHttpServletRequest();
        // 密码类型
        String passwdType = request.getParameter("passwdType");
        String password = request.getParameter("password");
        if (login != null && StringUtils.isNotBlank(passwdType)) {
            switch (passwdType) {
                // 动态密码(包括短信验证码/邮件验证码)
                case AuthConstant.PASSWD_TYPE_DYNAMIC:
                    login.setPassword(AccountService.encryptionPassword(password));
                    break;
                // 静态密码,保持数据库原有的既可
                case AuthConstant.PASSWD_TYPE_STATIC:
                default:
                    break;
            }
        }
        return login;
    }

    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}
